import {app,ipcMain,dialog} from 'electron'
const fs = require('fs');
const path = require('path');
const sd = require('silly-datetime');

const ipcMethods = () => {
  // 打开文件夹
  ipcMain.on("show-open-dialog", (event, data = {}) => {
    const option = {
      title: data.title || "选择要上传的文件",
      filters: data.filters || [{ name: "file", extensions: ["json"] }],
      buttonLabel: data.buttonLabel || "打开",
    };
    dialog.showOpenDialog(option).then((res) => {
      const filePath = res.filePaths[0];
      let fileSize = null;
      let fileContent = null;
      if (filePath) {
        const stat = fs.statSync(filePath);
        fileSize = stat.size / 1024 / 1024;
        if (fileSize <= 10) {
          const readFileSync = fs.readFileSync(filePath, "utf-8");
          fileContent = readFileSync.toString();
        }
      }
      event.sender.send("show-open-dialog", {
        filePath,
        fileSize,
        fileContent,
      });
    });
  });

  // 保存文件夹
  ipcMain.on("show-save-dialog", (event, data) => {
    const { fileContent } = data;
    const options = {
      title: "保存文件",
      defaultPath: `C:\\新建文件_${sd.format(
        new Date(),
        "YYYY-MM-DD-HH-mm-ss"
      )}.json`,
      filters: [{ name: "JSON", extensions: ["json"] }],
    };
    dialog
      .showSaveDialog(options)
      .then((result) => {
        const { canceled, filePath } = result;
        if (!canceled && filePath) {
          fs.writeFileSync(result.filePath, fileContent);
          const stat = fs.statSync(filePath);
          const fileSize = stat.size / 1024 / 1024;
          event.sender.send("show-save-dialog", {
            filePath,
            fileSize,
            fileContent,
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  });

  // 退出
  ipcMain.on("app-exit", (event, data) => {
    app.exit();
  });

  // 处理文件上传并保存到本地目录
  ipcMain.on("upload-file", (event, data) => {
    const { filePath, fileName } = data;
    let saveDir = "";
    if (process.env.NODE_ENV !== "development") {
      saveDir = process.resourcesPath;
    } else {
      saveDir = "E:\\work\\HTHT\\open-viewer\\static\\documents"; // 选择保存目录
    }
    const savePath = path.join(saveDir, fileName);
    // 确保保存目录存在
    if (!fs.existsSync(saveDir)) {
      fs.mkdirSync(saveDir);
    }

    // 读取文件内容并保存到指定目录
    fs.readFile(filePath, (err, data) => {
      if (err) {
        console.error("Error reading file:", err);
        return;
      }

      fs.writeFile(savePath, data, (err) => {
        if (err) {
          console.error("Error saving file:", err);
          return;
        }

        console.log(`File saved successfully to ${savePath}`);
        event.reply("file-saved", savePath); // 回复渲染进程，文件保存成功
      });
    });
  });
}

export default ipcMethods
